package com.zjxny.service;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendResult;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;

@Slf4j
@Service
public class WxCpZjServiceImpl implements WxCpZjService {
	
	@Value("${wechat.cp.corpId}")
	String corpId;
	
	@Value("${wechat.cp.secret}")
	String secretTxl;
	
	@Value("${wechat.cp.secret}")
	String tokenTxl;

	@Value("${wechat.cp.appConfigs[0].agentId}")
	Integer agentId;
	
	@Value("${wechat.cp.appConfigs[0].secret}")
	String secretApp = "";
	
	@Value("${wechat.cp.appConfigs[0].token}")
	String tokenApp = "";
	
	WxCpServiceImpl wxCpService;
	
	WxCpDefaultConfigImpl config;
	
	@PostConstruct
	void init() {
		this.config = new WxCpDefaultConfigImpl();
		this.config.setCorpId(corpId);      // 设置微信企业号的appid
		this.config.setCorpSecret(secretApp);  // 设置微信企业号的app corpSecret
		this.config.setAgentId(agentId);     // 设置微信企业号应用ID
		
		this.wxCpService = new WxCpServiceImpl();
		this.wxCpService.setWxCpConfigStorage(config);
		
		try {
			wxCpService.getAccessToken();
			this.config.setToken(tokenApp);       // 设置微信企业号应用的token
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void refreshAppToken() {
		try {
			this.tokenApp=wxCpService.getAccessToken(true);
			log.info("refresh.toekn={}",this.tokenApp);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void refreshTxlToken() {
		
	}

	@Override
	public WxCpMessageSendResult sendNotifyMessage(WxCpMessage message) {
		WxCpMessageSendResult result=null;
		try {
			result = wxCpService.getMessageService().send(message);
			log.info("send weixin cp message: {}",JSONUtil.toJsonStr(result));
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public WxCpMessageSendResult sendNotifyMessage(String toUser, String message) {
		WxCpMessage textMessage = WxCpMessage.TEXT().agentId(agentId).toUser(toUser).content(message).build();
		WxCpMessageSendResult result=null;
		try {
			result = wxCpService.getMessageService().send(textMessage);
			log.info("send weixin cp message: {}",JSONUtil.toJsonStr(result));
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		return result;
	}
}
